﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Web.Services;
using QuanLyHopDong.Biz;
using QuanLyHopDong.Biz.Model;
using QuanLyHopDong.Web.Common;
using Resources;

namespace QuanLyHopDong.Web.HopDong
{
    public partial class Edit : System.Web.UI.Page
    {
        #region Properties

        private static HopDongBiz _hopDongBiz;
        private static HopDongBiz HopDongManager
        {
            get { return _hopDongBiz ?? (_hopDongBiz = new HopDongBiz()); }
        }

        private EmployeeBiz _employeeBiz;
        private EmployeeBiz EmployeeManager { get { return _employeeBiz ?? (_employeeBiz = new EmployeeBiz()); } }

        private int _hopDongId;
        private int HopDongId
        {
            get
            {
                if (_hopDongId <= 0)
                    int.TryParse(Request.QueryString["Id"], out _hopDongId);
                return _hopDongId;
            }
        }

        private HopDongView _hopDongView;
        private HopDongView CurrentHopDongView
        {
            get
            {
                if (_hopDongView == null && HopDongId > 0)
                {
                    _hopDongView = HopDongManager.GetById(HopDongId);
                }
                return _hopDongView;
            }
        }

        #endregion

        #region Events

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                if (CurrentHopDongView == null)
                {
                    lblErrorMessage.Text = string.Format("{0}: Id={1}", GlobalStrings.NotExisted, HopDongId);
                    btnSave.Visible = false;
                    //lnkDeleteFile.Visible = false;
                    return;
                }
                
                if (!WebCommon.CurrrentEmployee.IsAdmin &&
                    WebCommon.CurrrentEmployee.Id != CurrentHopDongView.EmployeeId)
                {
                    Response.Redirect("~/NoPermission.aspx");
                    return;
                }

                LoadHopDongData();
            }
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            lblErrorMessage.Text = string.Empty;

            // validate input
            txtSoHopDong.Text = txtSoHopDong.Text.Trim();
            if (string.IsNullOrEmpty(txtSoHopDong.Text))
            {
                lblErrorMessage.Text = "Chưa nhập số hợp đồng";
                return;
            }

            #region Collect input

            var editHopDong = new Biz.Model.HopDong
            {
                Id = HopDongId,
                SoHopDong = txtSoHopDong.Text.Trim(),
                TenHopDong = txtTenHopDong.Text.Trim(),
                LoaiDuAn = txtLoaiDuAn.Text.Trim(),
                CreatedDate = DateTime.Now,
                ModifiedDate = DateTime.Now,
                CreatedBy = WebCommon.CurrrentEmployee.Id,
                ModifiedBy = WebCommon.CurrrentEmployee.Id,
                TenDonVi = txtTenDonVi.Text.Trim(),
                EmployeeId = int.Parse(ddlEmployees.SelectedValue)
            };

            DateTime ngayKy;
            if (DateTime.TryParseExact(txtNgayKy.Text.Trim(), GlobalStrings.DateFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out ngayKy))
            {
                editHopDong.NgayKy = ngayKy;
            }

            DateTime ngayBatDauThiCong;
            if (DateTime.TryParseExact(txtNgayBatDauThiCong.Text.Trim(), GlobalStrings.DateFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out ngayBatDauThiCong))
            {
                editHopDong.NgayBatDauThiCong = ngayBatDauThiCong;
            }

            DateTime ngayKetThucThiCong;
            if (DateTime.TryParseExact(txtNgayKetThucThiCong.Text.Trim(), GlobalStrings.DateFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out ngayKetThucThiCong))
            {
                editHopDong.NgayKetThucThiCong = ngayKetThucThiCong;
            }

            DateTime ngayHoanThien;
            if (DateTime.TryParseExact(txtNgayHoanThien.Text.Trim(), GlobalStrings.DateFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out ngayHoanThien))
            {
                editHopDong.NgayHoanThien = ngayHoanThien;
            }

            decimal giaTriHopDongChuaVat;
            if (decimal.TryParse(txtGiaTriHopDongChuaVAT.Text.Trim(), out giaTriHopDongChuaVat))
            {
                editHopDong.GiaTriHopDongChuaVAT = giaTriHopDongChuaVat;
            }

            decimal vat;
            if (decimal.TryParse(txtVat.Text.Trim(), out vat))
            {
                editHopDong.VAT = vat;
            }

            decimal giaTriVatTu;
            if (decimal.TryParse(txtGiaTriVatTu.Text.Trim(), out giaTriVatTu))
            {
                editHopDong.GiaTriVatTu = giaTriVatTu;
            }

            decimal giaTriNhanCong;
            if (decimal.TryParse(txtGiaTriNhanCong.Text.Trim(), out giaTriNhanCong))
            {
                editHopDong.GiaTriNhanCong = giaTriNhanCong;
            }

            decimal chiPhiKhac;
            if (decimal.TryParse(txtChiPhiKhac.Text.Trim(), out chiPhiKhac))
            {
                editHopDong.ChiPhiKhac = chiPhiKhac;
            }

            decimal tongGiaTriHopDong;
            if (decimal.TryParse(txtTongGiaTriHopDong.Text.Trim(), out tongGiaTriHopDong))
            {
                editHopDong.TongGiaTriHopDong = tongGiaTriHopDong;
            }

            //if (fileHopDong.HasFile)
            //{
            //    editHopDong.FileHopDong = Path.GetFileName(fileHopDong.PostedFile.FileName);
            //}

            //var fileName = string.Empty;
            //if (fileHopDong.HasFile)
            //{
            //    fileName = Path.GetFileName(fileHopDong.PostedFile.FileName);
            //    editHopDong.FileHopDong = fileName;
            //}
            //else
            //{
            //    editHopDong.FileHopDong = CurrentHopDongView.FileHopDong;
            //}

            editHopDong.TrangThai = int.Parse(ddlTrangThaiHopDong.SelectedValue);

            #endregion

            // delete old file
            //if (fileHopDong.HasFile)
            //{
            //    // delete old file
            //    if (!string.IsNullOrEmpty(CurrentHopDongView.FileHopDong))
            //    {
            //        var filePath =
            //            Server.MapPath(string.Format("~/Files/HopDong/{0}/{1}", CurrentHopDongView.Id,
            //                CurrentHopDongView.FileHopDong));
            //        HopDongManager.DeleteFileHopDong(filePath, CurrentHopDongView.Id);
            //    }
            //}

            // files
            var hopDongDocs = new List<HopDongDoc>();

            // file 1
            //var fileName = string.Empty;
            if (fileHopDong.HasFile)
            {
                hopDongDocs.Add(new HopDongDoc
                {
                    FileHopDong = Path.GetFileName(fileHopDong.PostedFile.FileName)
                });
                //fileName = Path.GetFileName(fileHopDong.PostedFile.FileName);
                //newHopDong.FileHopDong = fileName;
            }
            if (fileHopDong2.HasFile)
            {
                hopDongDocs.Add(new HopDongDoc
                {
                    FileHopDong = Path.GetFileName(fileHopDong2.PostedFile.FileName)
                });
            }
            if (fileHopDong3.HasFile)
            {
                hopDongDocs.Add(new HopDongDoc
                {
                    FileHopDong = Path.GetFileName(fileHopDong3.PostedFile.FileName)
                });
            }
            if (fileHopDong4.HasFile)
            {
                hopDongDocs.Add(new HopDongDoc
                {
                    FileHopDong = Path.GetFileName(fileHopDong4.PostedFile.FileName)
                });
            }

            editHopDong.HopDongDocs = hopDongDocs;

            // update hopdong
            try
            {
                HopDongManager.UpdateHopDong(editHopDong);
            }
            catch (ApplicationException appEx)
            {
                lblErrorMessage.Text = WebCommon.GetGlobalString(appEx.Message);
                return;
            }

            // upload files
            WebCommon.UploadFile(editHopDong.Id, fileHopDong);
            WebCommon.UploadFile(editHopDong.Id, fileHopDong2);
            WebCommon.UploadFile(editHopDong.Id, fileHopDong3);
            WebCommon.UploadFile(editHopDong.Id, fileHopDong4);

            // upload file
            //if (fileHopDong.HasFile)
            //{
            //    // create folder
            //    var folderPath = Server.MapPath(string.Format("~/Files/HopDong/{0}", editHopDong.Id));
            //    if (!Directory.Exists(folderPath))
            //        Directory.CreateDirectory(folderPath);

            //    // save new file
            //    var filePathFull = folderPath + "/" + fileName;
            //    if (File.Exists(filePathFull))
            //        File.Delete(filePathFull);
            //    fileHopDong.PostedFile.SaveAs(filePathFull);

            //    lnkFileHopDong.Text = fileName;
            //    lnkFileHopDong.NavigateUrl = string.Format("~/Files/HopDong/{0}/{1}", CurrentHopDongView.Id, fileName);
            //    lnkDeleteFile.Visible = true;
            //}

            lblErrorMessage.Text = GlobalStrings.UpdateSuccess;
        }

        #endregion

        #region Helpers

        private void LoadHopDongData()
        {
            if (CurrentHopDongView.ThiCongXong)
                ltrThiCongXong.Text = "Thi công xong, chờ hoàn công";

            txtTenDonVi.Text = CurrentHopDongView.TenDonVi;
            txtSoHopDong.Text = CurrentHopDongView.SoHopDong;
            txtTenHopDong.Text = CurrentHopDongView.TenHopDong;
            txtLoaiDuAn.Text = CurrentHopDongView.LoaiDuAn;
            txtNgayKy.Text = CurrentHopDongView.NgayKy.HasValue
                ? CurrentHopDongView.NgayKy.Value.ToString(GlobalStrings.DateFormat)
                : string.Empty;
            txtNgayBatDauThiCong.Text = CurrentHopDongView.NgayBatDauThiCong.HasValue
                ? CurrentHopDongView.NgayBatDauThiCong.Value.ToString(GlobalStrings.DateFormat)
                : string.Empty;
            txtNgayKetThucThiCong.Text = CurrentHopDongView.NgayKetThucThiCong.HasValue
                ? CurrentHopDongView.NgayKetThucThiCong.Value.ToString(GlobalStrings.DateFormat)
                : string.Empty;
            txtNgayHoanThien.Text = CurrentHopDongView.NgayHoanThien.HasValue
                ? CurrentHopDongView.NgayHoanThien.Value.ToString(GlobalStrings.DateFormat)
                : string.Empty;
            txtGiaTriHopDongChuaVAT.Text = string.Format("{0:N0}", CurrentHopDongView.GiaTriHopDongChuaVAT);
            txtTongGiaTriHopDong.Text = string.Format("{0:N0}", CurrentHopDongView.TongGiaTriHopDong);
            txtGiaTriVatTu.Text = string.Format("{0:N0}", CurrentHopDongView.GiaTriVatTu);
            txtGiaTriNhanCong.Text = string.Format("{0:N0}", CurrentHopDongView.GiaTriNhanCong);
            txtChiPhiKhac.Text = string.Format("{0:N0}", CurrentHopDongView.ChiPhiKhac);
            txtVat.Text = string.Format("{0:N0}", CurrentHopDongView.VAT);
            
            ddlTrangThaiHopDong.SelectedValue = string.Format("{0}", CurrentHopDongView.TrangThai);

            // Nhan vien
            var employees = EmployeeManager.GetAllEmployees();
            ddlEmployees.DataValueField = "Id";
            ddlEmployees.DataTextField = "Name";
            ddlEmployees.DataSource = employees;
            ddlEmployees.DataBind();
            ddlEmployees.SelectedValue = string.Format("{0}", CurrentHopDongView.EmployeeId);
        }

        /*
        private void LoadQuyetToan()
        {
            txtGiaTriQuyetToan.Text = string.Format("{0:0}", CurrentHopDongView.GiaTriQuyetToan);
            txtGiaTriVatTuQuyetToan.Text = string.Format("{0:0}", CurrentHopDongView.GiaTriVatTuQuyetToan);
            txtGiaTriNhanCongQuyetToan.Text = string.Format("{0:0}", CurrentHopDongView.GiaTriNhanCongQuyetToan);
            txtChiPhiKhacQuyetToan.Text = string.Format("{0:0}", CurrentHopDongView.ChiPhiKhacQuyetToan);
            txtGiaTriHopDongChuaVATQuyetToan.Text = string.Format("{0:0}", CurrentHopDongView.GiaTriHopDongChuaVATQuyetToan);
            txtVatQuyetToan.Text = string.Format("{0:0}", CurrentHopDongView.VATQuyetToan);
            txtTongGiaTriQuyetToan.Text = string.Format("{0:0}", CurrentHopDongView.TongGiaTriQuyetToan);
            txtNgayQuyetToan.Text = CurrentHopDongView.NgayQuyetToan.HasValue
                ? CurrentHopDongView.NgayQuyetToan.Value.ToString(GlobalStrings.DateFormat)
                : string.Empty;
        }
        */

        #endregion

        #region Web Methods

        [WebMethod(EnableSession = true)]
        public static object FileList(int hopDongId)
        {
            var results = HopDongManager.FileList(hopDongId);
            return new {Result = "OK", Records = results};
        }

        [WebMethod(EnableSession = true)]
        public static object FileDelete(int Id)
        {
            HopDongManager.FileDelete(Id);
            return new { Result = "OK"};
        }

        #endregion
    }
}